﻿using Xejen.Communication.Configuration;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.Json;

namespace Xejen.Communication.Socket.Configuration
{
    /// <summary>
    /// 表示Socket配置
    /// </summary>
    /// <creator>marc</creator>
    public class SocketConfig : CommunicationConfig<HeartbeatConfig>
    {
        /// <summary>
        /// 通信连接列表
        /// </summary>
        public List<ConnectionConfig> Connections { get; set; }

        /// <inheritdoc cref="SocketConfig"/>
        public SocketConfig()
        {

        }
    }

    /// <summary>
    /// 通信连接
    /// </summary>
    public class ConnectionConfig
    {
        /// <summary>
        /// 字符编码：默认UTF-8
        /// </summary>
        [System.Text.Json.Serialization.JsonIgnore]
        [Newtonsoft.Json.JsonIgnore]
        public Encoding Encoding { get; private set; } = Encoding.UTF8;

        private string _encodingName = Encoding.UTF8.HeaderName.ToUpper();
        /// <summary>
        /// 编码名称，默认：UTF-8
        /// </summary>
        public string EncodingName
        {
            get
            {
                return _encodingName;
            }
            set
            {
                _encodingName = value;
                try
                {
                    Encoding = Encoding.GetEncoding(_encodingName);
                }
                catch
                {
                    _encodingName = Encoding.UTF8.HeaderName.ToUpper();
                    Encoding = Encoding.UTF8;

                    Debug.WriteLine($"编码命名格式错误：{_encodingName}，无法正确识别为{nameof(Encoding)}对象");
                }
            }
        }

        /// <summary>
        /// 服务器地址
        /// </summary>
        public string ServerAddress { get; set; }

        /// <summary>
        /// 服务端端口
        /// </summary>
        public int ServerPort { get; set; }

        /// <summary>
        /// 可接收的最大缓冲数据量大小，默认：10 * 1024 * 1024 kb，即10Mb
        /// <para>
        /// 此参数仅用于：SocketAsyncEventArgs
        /// </para>
        /// </summary>
        public int MaxBufferSize { get; set; } = 10 * 1024 * 1024;

        /// <summary>
        /// 发送数据超时时间，单位：毫秒，默认：无限
        /// </summary>
        public int SendTimeout { get; set; } = System.Threading.Timeout.Infinite;
        /// <summary>
        /// 发送的缓冲区大小，单位：字节，默认：8192
        /// </summary>
        public int SendBufferSize { get; set; } = 8192;
        /// <summary>
        /// 接收数据超时时间，单位：毫秒，默认：无限
        /// </summary>
        public int ReceiveTimeout { get; set; } = System.Threading.Timeout.Infinite;
        /// <summary>
        /// 接收的缓冲区大小，单位：字节，默认：8192
        /// </summary>
        public int ReceiveBufferSize { get; set; } = 8192;

        /// <inheritdoc cref="Xejen.Communication.Socket.Configuration.ConnectMode"/>
        public ConnectMode ConnectMode { get; set; } = ConnectMode.Long;
    }
}
